package com.hunan.yllxy.service;

import com.hunan.yllxy.repostitory.dao.RoleDao;
import com.hunan.yllxy.repostitory.dao.UserInfoDao;
import com.hunan.yllxy.repostitory.dao.UserRoleDao;
import com.hunan.yllxy.repostitory.entity.Role;
import com.hunan.yllxy.repostitory.entity.UserInfo;
import com.hunan.yllxy.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;

@Slf4j
@Service
@Transactional
public class UserInfoService implements UserDetailsService {
    @Autowired
    UserInfoDao userInfoDao;
    @Autowired
    private ExcelUtils excelUtils;
    @Autowired
    UserRoleDao userRoleDAO;
    @Autowired
    RoleDao roleDAO;
    @Autowired
    PasswordEncoder passwordEncoder;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserInfo userInfo = userInfoDao.findByAccount(username);
        String userInfoId = userInfo.getId();
        List<String> roleIds = userRoleDAO.findByUserId(userInfoId);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (roleIds.size() > 0) {
            List<Role> roles = roleDAO.findByIds(roleIds);
            for (Role role : roles) {
                String name = role.getName();
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(name);
                authorities.add(authority);
            }
        }
        userInfo.setAuthorityList(authorities);
        return userInfo;
    }

}
